# !/usr/bin/env python
# encoding: utf-8


"""
  @author: gaogao
  @file: iv_sweep.py
  @time: 2022/3/9 13:35
  @desc:固定波长下iv_sweep
"""
import time
from ATS.hardwarescan import conf_file_manager
from ATS.application.LCR_App.U2722A_App import U2722A_App
from ATS.application.LASER_App.L8164B_App import L8164B_App
from ATS.application.LASER_App.N7786C_App import N7786C_App
from ATS.util.calcu_step_util import get_points_list
from matplotlib import pyplot as plt

name = "SMU4"
u2722a_app = U2722A_App(name)
print(u2722a_app)

name = "SS3"
l8164b_app = L8164B_App(name)

name = "SS1"
n7786c_app = N7786C_App(name)


def iv_sweep_test(l8164_power=12, wave_length=1340, u2722_channel=2, i_range="1mA", i_limit=0.001, i_nplc=1,
                  start_voltage=-5, stop_voltage=1, voltage_points=101):
    l8164b_app.set_power_unit()
    l8164b_app.set_power_value(l8164_power)
    l8164b_app.set_wave_length(wave_length)
    l8164b_app.output_on()
    x_data, y_data = u2722_test(u2722_channel, i_range, i_limit, i_nplc, start_voltage, stop_voltage, voltage_points)
    y_data = [abs(i) for i in y_data]
    plot_curve(x_data, y_data)
    # 测试完成后，关闭稳偏模式
    # n7786c_app.stop_logging_polcontroller()
    # n7786c_app.set_stabilization_mode(0)


def u2722_test(channel, current_range, current_limit, current_nplc, start_voltage, stop_voltage, voltage_points):
    u2722a_app.set_voltage_range(channel)
    u2722a_app.set_current_range_limit(current_range, current_limit, channel)
    result_list = []
    u2722a_app.set_current_nplc(current_nplc, channel)
    voltage_list = get_points_list(start_voltage, stop_voltage, voltage_points)
    u2722a_app.output_state(1, channel)
    for i in voltage_list:
        u2722a_app.set_voltage(round(i, 3), channel)
        result = u2722a_app.get_current_value(channel)
        result_list.append(float(result))
    u2722a_app.output_state(0, channel)
    return voltage_list, result_list


def plot_curve(x_data, y_data):
    print(x_data, y_data)
    plt.yscale('log')
    plt.gca().invert_xaxis()
    plt.plot(x_data, y_data, "b")
    plt.xlabel("Voltage")
    plt.ylabel("Value")
    plt.grid(True)
    plt.show()


# print(type(locals()['para']), locals()['para'][0].smu_setting)
# print(locals()['para'][0].l8164_setting)
iv_sweep_test()
